package com.orangelife.service.propFeeComm.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.github.pagehelper.PageHelper;
import com.orangelife.common.MybaitsGenericDaoSubLogic;
import com.orangelife.exception.AppBizException;
import com.orangelife.service.PropFeeType.IPropFeeTypeService;
import com.orangelife.service.cerHouseholder.ICerHouseholderService;
import com.orangelife.service.cerHouseholder.model.CerHouseholderDto;
import com.orangelife.service.propFeeComm.IPropFeeCommService;
import com.orangelife.service.propFeeComm.model.PayBillInfo;
import com.orangelife.service.propFeeComm.model.PropFeeCommDto;
import com.orangelife.service.propFeeDic.IPropFeeDicService;
import com.orangelife.service.propFeeDic.model.PropFeeDicDto;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.setting.constant.TypeConst;
import com.orangelife.utils.DateStyle;
import com.orangelife.utils.DateUtil;
import com.orangelife.utils.HttpSvcUtils;
import com.orangelife.utils.IdUtil;
import com.orangelife.utils.JSONHelper;
import com.orangelife.utils.JsonMapUtils;
import com.orangelife.utils.ProConfig;
import com.orangelife.utils.StringUtils;
import com.orangelife.utils.UrlPath;

/*****************************************************************
 * Copyright(C) ORANGELIFE Corporation CodeConst.BIS_CODE_68001015. All Rights
 * Reserved.
 *****************************************************************/
/*
 * ============================================================== 功能名
 * PropFeeComm类的 service层的增删改查
 * 
 * @author @author zhr
 * 
 * @version 1.1.0
 * 
 * @date 2016-08-04 19:40:50
 * ==============================================================
 */
@Service("propFeeCommService")
public class PropFeeCommServiceImpl extends MybaitsGenericDaoSubLogic implements
		IPropFeeCommService {

	@Resource(name = "cerHouseholderService")
	private ICerHouseholderService cerHouseholderService;
	@Resource(name = "propFeeTypeService")
	private IPropFeeTypeService propFeeTypeService;
	@Resource(name = "propFeeDicService")
	private IPropFeeDicService propFeeDicService;

	private static Logger logger = Logger
			.getLogger(PropFeeCommServiceImpl.class);

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		PropFeeCommServiceImpl.logger = logger;
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int addPropFeeComm(PropFeeCommDto propFeeComm)
			throws AppBizException {

		Assert.notNull(propFeeComm);
		/************************************************
		 * 判断输入参数的长度以及是否能为空
		 ************************************************/

		if (!StringUtils.isBlank(propFeeComm.getComm())) {
			if (propFeeComm.getComm().length() > 128) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "小区名称长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeComm.getRemark())) {
			if (propFeeComm.getRemark().length() > 512) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "备注长度超出");
			}
		}

		if (StringUtils.isBlank(propFeeComm.getCommID())) {
			propFeeComm.setCommID(IdUtil.getuuId());
		}

		List<PropFeeCommDto> propFeeCommDtos = this
				.findPropFeeCommByRelevantID(
						propFeeComm.getCommID().toString(),
						propFeeComm.getComm());

		if (propFeeCommDtos != null && propFeeCommDtos.size() > 0) {
			throw new AppBizException(2, "亲 ，已经存在");
		}
		propFeeComm.setItemStat(TypeConst.FLAG_ON);

		return this.getSqlSession().insert("PropFeeCommMapper.insertSelective",
				propFeeComm);
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int editPropFeeComm(PropFeeCommDto propFeeComm)
			throws AppBizException {

		Assert.notNull(propFeeComm);
		/************************************************
		 * 判断输入参数的长度以及是否能为空
		 ************************************************/
		if (StringUtils.isBlank(propFeeComm.getCommID())) {
			throw new AppBizException(CodeConst.SYS_CODE_1001, "ID不可为空");
		}
		PropFeeCommDto oldPropFeeComm = this.findPropFeeCommByID(propFeeComm
				.getCommID());

		if (!StringUtils.isBlank(propFeeComm.getComm())) {
			if (propFeeComm.getComm().length() > 128) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "小区名称长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeComm.getRemark())) {
			if (propFeeComm.getRemark().length() > 512) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "备注长度超出");
			}
		}

		if (oldPropFeeComm == null) {
			throw new AppBizException(CodeConst.BIS_CODE_68001,
					InfoConst.BIS_INFO_68001);
		}

		List<PropFeeCommDto> propFeeCommDtos = this
				.findPropFeeCommByRelevantID(
						propFeeComm.getCommID().toString(),
						propFeeComm.getComm());

		if (propFeeCommDtos != null && propFeeCommDtos.size() > 1) {
			throw new AppBizException(2, "亲 ，已经存在");
		}

		if (propFeeCommDtos.size() == 1) {

			if (!propFeeCommDtos.get(0).getCommID()
					.equals(oldPropFeeComm.getCommID())) {
				throw new AppBizException(2, "亲 ，已经存在");
			}
		}

		if (!StringUtils.isBlank(propFeeComm.getFinfo())) {
			oldPropFeeComm.setFinfo(propFeeComm.getFinfo());
		}
		if (!StringUtils.isBlank(propFeeComm.getComm())) {
			oldPropFeeComm.setComm(propFeeComm.getComm());

		}
		if (!StringUtils.isBlank(propFeeComm.getRemark())) {
			oldPropFeeComm.setRemark(propFeeComm.getRemark());

		}

		if (!StringUtils.isBlank(propFeeComm.getQrcode())) {
			oldPropFeeComm.setQrcode(propFeeComm.getQrcode());

		}
		return this.getSqlSession()
				.update("PropFeeCommMapper.updateByPrimaryKeySelective",
						oldPropFeeComm);
	}

	@Override
	public PropFeeCommDto findPropFeeCommByID(String propFeeCommID)
			throws AppBizException {
		if (StringUtils.isBlank(propFeeCommID)) {

			throw new AppBizException(CodeConst.SYS_CODE_1001, "ID不可为空");
		}

		/************************************************
		 * 判断实体是否存在
		 ************************************************/
		PropFeeCommDto oldPropFeeComm = this.getSqlSession().selectOne(
				"PropFeeCommSearchMapper.selectByPrimaryKey", propFeeCommID);
		if (oldPropFeeComm == null) {
			throw new AppBizException(CodeConst.BIS_CODE_68001,
					InfoConst.BIS_INFO_68001);
		}

		if (TypeConst.FLAG_OFF.equals(oldPropFeeComm.getItemStat())) {

			throw new AppBizException(CodeConst.BIS_CODE_68001,
					InfoConst.BIS_INFO_68001);
		}
		return oldPropFeeComm;
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int deletePropFeeCommByLogic(String propFeeCommID)
			throws AppBizException {

		if (StringUtils.isBlank(propFeeCommID)) {
			throw new AppBizException(CodeConst.SYS_CODE_1001, "ID不可为空");
		}
		/************************************************
		 * 判断实体是否存在
		 ************************************************/
		PropFeeCommDto oldPropFeeComm = this.findPropFeeCommByID(propFeeCommID);

		oldPropFeeComm.setItemStat(TypeConst.FLAG_OFF);

		return this.getSqlSession()
				.update("PropFeeCommMapper.updateByPrimaryKeySelective",
						oldPropFeeComm);
	}

	@Override
	@Cacheable(value = "propFeeCommInfos")
	public List<Map<String, Object>> findPropFeeCommByPage(String tsCreate,
			String search, int pageNo, int pageSize) throws AppBizException {

		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tsCreate", tsCreate);
		map.put("search", search);
		PageHelper.startPage(pageNo, pageSize);
		List<Map<String, Object>> list = this.getSqlSession().selectList(
				"PropFeeCommSearchMapper.findAllPropFeeComm", map);
		return list;
	}

	@Override
	public List<PropFeeCommDto> getPropFeeCommByPage(String tsCreate,
			String search, int pageNo, int pageSize) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tsCreate", tsCreate);
		map.put("search", search);
		PageHelper.startPage(pageNo, pageSize);
		List<PropFeeCommDto> list = this.getSqlSession().selectList(
				"PropFeeCommSearchMapper.getAllPropFeeCommDto", map);
		return list;
	}

	@Override
	public List<Map<String, Object>> selectPropFeeCommByRelevantID(String commID)
			throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("commID", commID);

		List<Map<String, Object>> list = this.getSqlSession().selectList(
				"PropFeeCommSearchMapper.selectPropFeeCommDtoyRelevantID", map);
		return list;
	}

	@Override
	public List<PropFeeCommDto> findPropFeeCommByRelevantID(String commID,
			String comm) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("commID", commID);
		map.put("comm", comm);

		List<PropFeeCommDto> list = this.getSqlSession().selectList(
				"PropFeeCommSearchMapper.findPropFeeCommDtoByRelevantID", map);
		return list;
	}

	@Override
	public List<PropFeeCommDto> bauthfindPropFeeComm(List<String> propFeeCommIDs)
			throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		List<PropFeeCommDto> list = this.getSqlSession().selectList(
				"PropFeeCommSearchMapper.batchFindPropFeeComm", propFeeCommIDs);
		return list;
	}

	@Override
	@Cacheable(value = "bauthPropFeeComms")
	public List<Map<String, Object>> bauthfindPropFeeCommByMap(
			Map<String, Object> propFeeComm) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		List<Map<String, Object>> list = this.getSqlSession().selectList(
				"PropFeeCommSearchMapper.batchFindPropFeeCommByMap",
				propFeeComm);
		return list;
	}

	@Override
	public void clearCache() throws AppBizException {
		System.out.println("清除缓存成功");
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int bauthDeleteComm(List<String> commIDs) throws AppBizException {
		return this.getSqlSession().update(
				"PropFeeCommBauthMapper.bauthDeleteLg", commIDs);
	}

	@Override
	public PayBillInfo getPayBillInfo(PayBillInfo payBillInfo)
			throws AppBizException {
		/***
		 * 立即发送到财务中心
		 */
		String rightSend = ProConfig.getProValues("RIGHTSEND");
		if (!rightSend.equals("1")) {
			throw new AppBizException(2, "亲，没有开通立即发送信息");
		}

		if (StringUtils.isBlank(payBillInfo.getCommID())) {
			throw new AppBizException(2, "亲，小区信息");
		}

		List<String> commIDs = new ArrayList<String>();

		commIDs.add(payBillInfo.getCommID());
		List<PropFeeCommDto> propFeeCommDtos = this
				.bauthfindPropFeeComm(commIDs);

		if (propFeeCommDtos == null) {
			throw new AppBizException(2, "亲，小区信息");
		}
		/****
		 * {"id":2,"project":"","projectCode":"","compName":"","ROW_ID":2,
		 * "compfname"
		 * :"厦门新凯宾物业服务有限公司(本部)","compfnumber":"01.01.01.01","compCode"
		 * :"","fname":"厦门新凯宾源昌豪庭","fnumber":"01.01.06"}
		 */

		if (StringUtils.isBlank(propFeeCommDtos.get(0).getFinfo())) {
			throw new AppBizException(2, "亲，该小区未开通");
		}
		payBillInfo.setPmCommID(payBillInfo.getCommID());

		Map<String, Object> fInfo = JSONHelper.jsonToMap(propFeeCommDtos.get(0)
				.getFinfo());

		payBillInfo.setCompID(fInfo.get("compName") != null ? fInfo.get(
				"compName").toString() : null);

		payBillInfo.setCommID(fInfo.get("fnumber") != null ? fInfo.get(
				"fnumber").toString() : null);
		if (!StringUtils.isBlank(payBillInfo.getApartmentID())) {
			Map<String, Object> propFeeComm = cerHouseholderService
					.getHouseInfo(payBillInfo.getApartmentID());
			StringBuffer houseInfo = new StringBuffer();
			houseInfo.append(propFeeComm.get("buildingName") + "-");
			if (propFeeComm.get("unitName") != null) {
				houseInfo.append(propFeeComm.get("unitName")).append("-");
			}
			houseInfo.append(propFeeComm.get("apartmentNum"));

			if (propFeeComm.get("ownerName") != null) {
				houseInfo.append("(").append(propFeeComm.get("ownerName"))
						.append(")");
			}
			payBillInfo.setBuild(houseInfo.toString());
			payBillInfo
					.setApartment(propFeeComm.get("apartmentNum").toString());

			if (StringUtils.isBlank(payBillInfo.getPayUserID())
					|| StringUtils.isBlank(payBillInfo.getPayPhone())) {
				List<CerHouseholderDto> cerHouseholderDtos = cerHouseholderService
						.findCerHouseholderByRelevantID(null,
								payBillInfo.getApartmentID(), null, null, null,
								null, null);
				for (CerHouseholderDto cerHouseholderDto : cerHouseholderDtos) {
					if (cerHouseholderDto.getName().equals(
							propFeeComm.get("ownerName").toString())) {
						payBillInfo.setPayPhone(cerHouseholderDto.getPhone());
						payBillInfo.setPayUserID(cerHouseholderDto
								.getLinkAptHouseholderID());
						payBillInfo.setPayUserName(cerHouseholderDto.getName());
					}
				}
			}
		}

		if (payBillInfo.getFeeTypeDto() != null) {
			payBillInfo.setTypeCode(payBillInfo.getFeeTypeDto().getFnumber());
		}
		if (!StringUtils.isBlank(payBillInfo.getChargeType())) {
			payBillInfo.setChargeType(getPayCode(payBillInfo.getChargeType()));
		}

		if (!StringUtils.isBlank(payBillInfo.getTsBill())) {
			payBillInfo.setTsBill(DateUtil.DateToString(
					new Date(Long.parseLong(payBillInfo.getTsBill())),
					DateStyle.YYYY_MM_DD_HH_MM_SS));
		}

		if (!StringUtils.isBlank(payBillInfo.getTsCharge())) {
			payBillInfo.setTsCharge(DateUtil.DateToString(
					new Date(Long.parseLong(payBillInfo.getTsCharge())),
					DateStyle.YYYY_MM_DD_HH_MM_SS));
		}

		if (!StringUtils.isBlank(payBillInfo.getRemarkType())) {
			if (!StringUtils.isBlank(payBillInfo.getPayUserName())) {
				payBillInfo.setRemark("用户:" + payBillInfo.getPayUserName()
						+ payBillInfo.getRemark());
			}
		}
		try {
			List<Map<String, Object>> pmInfo = JsonMapUtils
					.getPageEntityMap(HttpSvcUtils.doPostSvc(UrlPath.bauthComm,
							commIDs, null));
			if (pmInfo != null && pmInfo.size() > 0) {
				payBillInfo.setPmID(pmInfo.get(0).get("pmID").toString());
			}
		} catch (Exception e) {

		}

		return payBillInfo;
	}

	public String getPayCode(String payWay) throws AppBizException {

		String payCode = "";
		List<PropFeeDicDto> propFeeDics = propFeeDicService
				.findPropFeeDicByRelevantID(null, null, "PAYTYPE");
		if (propFeeDics == null || propFeeDics.size() <= 0) {
			throw new AppBizException(2, "缴费支付方式");
		}

		/**
		 * 
		 * 结算方式（'0现金',1 '刷卡',2 '银行转账', 3"橙子生活代缴",4 "支付宝缴费",5,折减优惠,6押金转存，7预存冲抵）*
		 **/

		for (PropFeeDicDto propFeeDicDto : propFeeDics) {
			if (propFeeDicDto.getName().equals(payWay)) {
				payCode = propFeeDicDto.getVal();
			}

		}

		/*
		 * switch (payWay) {
		 * 
		 * case "0":
		 * 
		 * payCode = "A001"; break; case "1":
		 * 
		 * payCode = "A002"; break; case "2":
		 * 
		 * payCode = "A003"; break; case "3":
		 * 
		 * payCode = "A005"; break;
		 * 
		 * case "4":
		 * 
		 * payCode = ""; break; case "5":
		 * 
		 * payCode = ""; break;
		 * 
		 * case "6":
		 * 
		 * payCode = "A004"; break; case "7":
		 * 
		 * payCode = "A010"; break;
		 * 
		 * default: break; }
		 */
		return payCode;
	}
}